package com.i2works.smartluolong.manage.controller.user;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.manage.utils.BaseModule;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.base.URLConstant;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.common.SelectDO;
import com.i2works.smartluolong.web.entity.user.*;
import com.i2works.smartluolong.web.service.user.IUserAccountExtendService;
import com.i2works.smartluolong.web.service.user.IUserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 会员基础信息
 *
 * @author Liu Yutao
 * @className UserRoleController
 * @email koal@vip.qq.com
 * @date 2016/2/6 17:19
 */

@Controller
@RequestMapping("/userAccount")
public class UserAccountController extends BaseModule {

    @Autowired
    private IUserAccountService userAccountService;

    @Autowired
    private IUserAccountExtendService userAccountExtendService;


    /**
     * 普通会员管理页面
     */
    @GetMapping(value = "/view/index")
    public String index() {
        logger.info("普通会员管理页面");
        return URLConstant.User.USER_URL;
    }

    /**
     * 查询普通会员列表
     */
    @GetMapping(value = "/view/api")
    @ResponseBody
    public Result queryList(@ModelAttribute UserAccountQuery query) {
        Result result = new Result();
        try {
            int total = userAccountService.queryCount(query);
            List<UserAccountVO> voList = Lists.newArrayList();
            if (total > 0) {
                List<UserAccountDO> detailsList = userAccountService.queryList(query);
                voList = BaseUtils.do2voList(detailsList, UserAccountVO.class);
            }
            return R.success(voList, total);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.SYSTEM_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 编辑新增页面跳转
     */
    @GetMapping("/update/{id}")
    public String updatePage(@PathVariable Integer id, Model model) {
        try {
            getUser(id, model);
        } catch (Exception e) {
            logger.error("", e.getMessage());
        }
        logger.info("会员编辑");
        return URLConstant.User.USER_SAVE_URL;
    }

    //获取信息
    private void getUser(Integer id, Model model) throws ServiceException {
        try {
            if (id != null) {
                UserAccountQuery query = new UserAccountQuery();
                query.setId(id);
                UserAccountDO userAccount = userAccountService.query(query);
                model.addAttribute("userAccount", userAccount);

                UserAccountExtendQuery extendQuery = new UserAccountExtendQuery();
                extendQuery.setUserId(id);
                UserAccountExtendDO userAccountExtendDO = userAccountExtendService.query(extendQuery);
                model.addAttribute("userAccountExtend", userAccountExtendDO);
            }
        } catch (Exception e) {
           throw new ServiceException(e);
        }
    }

    /**
     * 会员新增页面跳转
     */
    @GetMapping(value = "/save/index")
    public String savePage() {
        logger.info("会员新增");
        return URLConstant.User.USER_SAVE_URL;
    }


    /**
     * 编辑或新增会员
     */
    @PostMapping("/save/action")
    @ResponseBody
    public Result save(@ModelAttribute UserAccountDO userAccount) {
        Result result = new Result();
        try {
            userAccount.setUpdateName(getUserName());
            userAccountService.save(userAccount);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.EDIT_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 会员信息页面跳转
     */
    @GetMapping(value = "/view/{id}")
    public String userViewPage(@PathVariable Integer id, Model model) {
        try {
            getUser(id, model);
        } catch (ServiceException e) {
            logger.error("", e.getMessage());
        }
        logger.info("会员信息");
        return URLConstant.User.USER_VIEW_URL;
    }


    /**
     * 更新状态
     */
    @PostMapping("/status/action")
    @ResponseBody
    public Result updateStatus(@ModelAttribute UserAccountDO userAccount) {
        Result result = new Result();
        try {
            userAccount.setUpdateName(getUserName());
            userAccountService.updateStatus(userAccount);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.STATUS_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 批量更改状态
     */
    @PostMapping("/status/batchAction")
    @ResponseBody
    public Result updateBatchStatus(@RequestParam("idsList[]") List<Long> idsList, Integer status) {
        Result result = new Result();
        try {
            if (idsList != null && idsList.size() > 0) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("idsList", idsList);
                map.put("status", status);
                map.put("updateName", getUserName());
                userAccountService.updateBatchStatus(map);
            }
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.STATUS_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 修改密码
     */
    @PostMapping("/password/action")
    @ResponseBody
    public Result updatePassword(@ModelAttribute UserAccountDO userAccount) {
        Result result = new Result();
        try {
            userAccount.setUpdateName(getUserName());
            userAccount.setPassword(GlobalConstant.DEFAULT_PASSWORD);
            userAccountService.updatePassword(userAccount);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.SAVE_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 批量密码修改
     */
    @PostMapping("/password/batchAction")
    @ResponseBody
    public Result updateBatchPassword(@RequestBody List<UserAccountDO> userAccountList) {
        Result result = new Result();
        try {
            if (userAccountList != null && userAccountList.size() > 0) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("userAccountList", userAccountList);
                map.put("updateName", getUserName());
                userAccountService.updateBatchPassword(map);
            }

        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.STATUS_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 编辑新增页面跳转
     */
    @GetMapping("/view/roleSelect/{id}")
    @ResponseBody
    public Result queryRoleSelect(@PathVariable Integer id) {
        Result result = new Result();
        try {
            if (id != null) {
                List<SelectDO> roleSelect = userAccountService.queryRoleSelect(id);
                result.setRows(roleSelect);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 某个账号和邮箱是否存在验证
     */
    @PostMapping("/view/check")
    public boolean queryCheck(@ModelAttribute UserAccountQuery query) {
        boolean result = false;
        try {
            int count = userAccountService.queryCheck(query);
            if (count <= 0) {
                result = true;
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }

    /**
     * 删除
     */
    @PostMapping("/delete/action")
    @ResponseBody
    public Result delete(@RequestParam Integer id) {
        Result result = new Result();
        try {
            userAccountService.delete(id);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.DELETE_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 批量删除
     */
    @PostMapping("/delete/batchAction")
    @ResponseBody
    public Result deleteBatch(@RequestParam("idsList[]") List<Integer> idsList) {
        Result result = new Result();
        try {
            if (idsList != null && idsList.size() > 0) {
                userAccountService.deleteBatch(idsList);
            }
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.DELETE_ERROR.getMsg());
        }
        return result;
    }


}
